import json

class OperationJson():

    #读取json文件
    def read_data(self,file_path):
        with open(file_path, encoding='utf-8') as fp:#打开json文件
            data = json.load(fp)#读取json数据
            return data

    #根据关键字获取数据,id代表关键字
    def get_data(self, file_path, id):
        return self.read_data(file_path)[id]

    #写cookie json
    def write_cookie_data(self,data):
        with open('../data/cookie.json','wb') as fp:#打开cookie文件
            fp.write(data)

    #写token
    def write_token_data(self,data):
        with open ('../data/token.json','wb') as fp:
            fp.write(data)

    #变更json文件的值
    def check_json_value(self,dict_json,k,v):#dict_json为读取到的json,k设为变量key，v设为变量value
        if isinstance(dict_json,dict):#判断是否是字典类型，instance返回true,false
            for key in dict_json:#遍历key
                if key==k:#如果变量k是json里边的key,则给k赋值v
                    dict_json[key]=v
                elif isinstance(dict_json[key],dict):#如果dict_json[key]依旧是字典类型
                    self.check_json_value(dict_json[key],k,v)#递归
        return dict_json

    def get_new_json(self,file_path,key,value):
        key_=key.split(".")
        key_length=len(key_)
        with open(file_path,'rb') as f:
            json_data=json.load(f)#读取json数据
            i=0
            a=json_data
            while i<key_length :
                if i+1==key_length :
                    a[key[i]]=value
                    i=i+1
                else:
                    a=a[key[i]]
                    i=i+1
        f.close()
        return json_data

#重写json文件json的值
    def rewrite_json_file(self,file_path,json_data):
        with open(file_path ,'w') as f:
            json.dump(json_data,f)
        f.close()


#调试
if __name__=='__main__':
    opjson = OperationJson()
    file = '../data/request_data.json'
    id = 'worker_info'
    data_json = opjson.get_data(file_path=file, id=id)
    key = 'ServiceProviderWorkOrderSave[id]'
    value = 350
    m_json_data=opjson.get_new_json(file,key,value)
    print("--------------%s"%m_json_data)
    # opjson.rewrite_json_file(file,m_json_data)




